<template>
    <div ref="terminalBox" style="height: 100vh;"></div>
</template>

<script setup>
import 'xterm/css/xterm.css'
import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import { ref, onMounted } from 'vue'
// import 'nora-zmodemjs'
import { useMessage } from "naive-ui";
import CryptoJS from "crypto-js";

import getUrl from '../../../net/getUrl'

const message = useMessage();
let terminalBox = ref(null)
let term
let socket


function changFileList(f) {
    fileList.value = f.fileList
}

// dom 挂载后 回调
onMounted(() => {
    //创建一个客户端
    term = new Terminal({
        rendererType: 'canvas', //使用这个能解决vim不显示或乱码
        cursorBlink: true,
        cursorStyle: "bar",
    })
    // term.write
    // 将客户端挂载到dom上
    const fitAddon = new FitAddon()
    term.loadAddon(fitAddon)
    term.open(terminalBox.value)
    fitAddon.fit()

    // 创建socket连接
    term.write('正在连接...\r\n');
    // 获取当前请求的主机跟账号
    let id = getUrl(window.location, 'id')

    socket = new WebSocket('ws://127.0.0.1:8080/replayer/tui/' + id + '?Authorization=' + window.sessionStorage.getItem('Authorization'))
    // socket = new WebSocket('ws://162.14.109.53:8080/myssh')
    socket.binaryType = "arraybuffer"

    // 打开socket监听事件的方法
    socket.onopen = function () {
        fitAddon.fit()
    }
    socket.onclose = function () {
        term.writeln('\r\n连接关闭');
    }
    socket.onerror = function (err) {
        term.writeln('读取数据异常：', err);
    }
    // 接收数据
    socket.onmessage = function (recv) {
        try {
            // new TextDecoder().decode(recv.data)
            let msg = JSON.parse(recv.data);
            // term.write(new TextDecoder().decode(recv.data))
            term.write(CryptoJS.enc.Base64.parse(msg.data).toString(CryptoJS.enc.Utf8))

        } catch (e) {
            if (typeof recv.data === 'string') {
                
                let data = recv.data.split('"data":"')
                if (data.length > 0) {
                    let datacon = data[data.length - 1].split('"')
                    if (datacon.length > 0) {
                        // console.log(datacon[0])
                        message.warning('读取数据有乱码！')
                        term.write(atob(datacon[0]))
                    }
                }
            }
        }

    }
     window.addEventListener("resize", () => {
        fitAddon.fit()
    }, false)

})

</script>

<style scoped>
</style>